package com.ruix.app.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMError;
import com.ruix.app.R;
import com.ruix.app.util.VoiceRecorder;
import com.ruix.app.widget.chatrow.ChatRowVoicePlayClickListener;

/**
 * Created by hadexs on 2017/6/17.
 */

public class LessonInputVoiceView extends RelativeLayout implements GestureDetector.OnGestureListener {


    private int colorBlue = 0xFF3F85EA;
    private int colorRed = 0xFFFF6565;
    private int colorOrange = 0xFFFF983F;

    private int colorAlphaBlue = 0xAA3F85EA;
    private int colorAlphaOrange = 0xAAFF983F;
    private int colorDefault = 0xFFF6F6F6;


    private float topInterval;


    private TextView voiceModelFirst, voiceModelSecend, voiceModelThree;
    private TextView voiceTime, voiceCancle,voiceSendText;
    private View voicePointView;
    private GestureDetector detector;
    private VoiceInputModel currentModle; //单击初始化 1 点击录音中 3  单击暂停 4   长按初始化 2 长按发送语音中 5
    private RelativeLayout actionView;
    private ImageView circleBg,longClickBg;
    private VoiceProgressView  progressView;
    private CountDownTimer countDownTimer; //
    private int times; //
    private VoiceInputListener voiceInputListener;
    private float distanceScrollX, distanceScrollY;

    private String voicePath;
    private Context mContext;
    private int voiceLength;

//    private float downX, downY, distanceX, distanceY;

    protected VoiceRecorder voiceRecorder;
    protected PowerManager.WakeLock wakeLock;

    private VoiceRecorderCallback voiceRecorderCallback;

    public LessonInputVoiceView(Context context) {
        super(context);
        initView(context);
    }

    public LessonInputVoiceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public LessonInputVoiceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }


    private void initView(Context context) {
        this.mContext = context;
        LayoutInflater.from(context).inflate(R.layout.layout_lesson_voice_input, this, true);
        voiceCancle = (TextView) findViewById(R.id.tv_voice_cancle);
        voiceTime = (TextView) findViewById(R.id.tv_voice_total_time);
        voicePointView = findViewById(R.id.voice_point);
        voiceModelFirst = (TextView) findViewById(R.id.tv_voice_model_first);
        voiceModelSecend = (TextView) findViewById(R.id.tv_voice_model_secend);
        voiceModelThree = (TextView) findViewById(R.id.tv_voice_model_threed);

        //
        actionView =  (RelativeLayout)findViewById(R.id.voice_action_view);
        circleBg = (ImageView) findViewById(R.id.voice_view_circle_bg);
        longClickBg = (ImageView) findViewById(R.id.voice_view_long_click);

        voiceSendText = (TextView) findViewById(R.id.tv_voice_send_text);

        progressView = (VoiceProgressView) findViewById(R.id.voice_progress);

        topInterval = context.getResources().getDimension(R.dimen.h_w_50);

//        voiceTime.setVisibility(INVISIBLE);
//        detector = new GestureDetector(context, this);

        voiceRecorder = new VoiceRecorder();
        voiceRecorder.initPath(context);
        wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");

        showClickModel();
        setListener();
    }


    private void setListener() {
        voiceModelFirst.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchVoiceModel();
            }
        });

        voiceModelThree.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchVoiceModel();
            }
        });

        circleBg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentModle == VoiceInputModel.InitClick){
                    startClickRecording();
                } else if (currentModle == VoiceInputModel.ClickVoiceing){
                    pauseClickRecording();
                } else if (currentModle == VoiceInputModel.ClickVoicePause){
                    sendClickRecording();
                }

            }
        });

        voiceCancle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                cancleClickRecording();
            }
        });

        longClickBg.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (currentModle == VoiceInputModel.InitLongClick
                        ||currentModle == VoiceInputModel.LongClickVoiceing){
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            if (currentModle == VoiceInputModel.InitLongClick) {
                                startLongClickRecording();
                            }
                            break;

                        case MotionEvent.ACTION_MOVE:
                            if (currentModle == VoiceInputModel.LongClickVoiceing) {
                                if (event.getY() < -topInterval) {
                                    if (voiceInputListener != null) {
                                        voiceInputListener.showVoiceInputTip("松开手指，取消发送", colorRed);
                                    }
                                } else {
                                    if (voiceInputListener != null) {
                                        voiceInputListener.showVoiceInputTip("手指滑向此区域，取消录音", 0xFF56B4F4);
                                    }
                                }
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            if (currentModle == VoiceInputModel.LongClickVoiceing) {
                                if (event.getY() < -topInterval) {
                                    cancelLongClickRecording();
                                } else {
                                    finishLongClickRecording();
                                }
                            }

                            break;
                    }
                    return true;
                }

                return false;
            }
        });

    }


    //单击模式
    private void showClickModel() {
        currentModle = VoiceInputModel.InitClick;
        voiceModelFirst.setVisibility(INVISIBLE);
        voiceModelThree.setVisibility(VISIBLE);
        voiceModelSecend.setText("单击模式");
        voiceModelSecend.setTextColor(colorRed);//#
        voicePointView.setBackgroundResource(R.drawable.shape_voice_red_circle);
        circleBg.setBackgroundResource(R.drawable.shape_voice_red_circle);
        circleBg.setImageDrawable(null);
        voiceSendText.setVisibility(GONE);
        voiceCancle.setVisibility(GONE);
        voiceTime.setTextColor(colorOrange);
        voiceTime.setText("");
        actionView.setBackgroundResource(R.drawable.shape_voice_de_circle);
        progressView.setProgressColor(colorAlphaOrange);
        progressView.setVisibility(VISIBLE);
        progressView.setProgress(0);

        longClickBg.setVisibility(GONE);
        circleBg.setVisibility(VISIBLE);

        if (voiceInputListener != null){
            voiceInputListener.hideVoiceInputTip();
        }
    }


    //长按模式
    private void showLongClickModel() {
        currentModle = VoiceInputModel.InitLongClick;
        voiceModelThree.setVisibility(INVISIBLE);
        voiceModelFirst.setVisibility(VISIBLE);
        voiceModelSecend.setText("长按模式");
        voiceModelSecend.setTextColor(colorBlue);
        voicePointView.setBackgroundResource(R.drawable.shape_voice_blue_circle);
        //

        actionView.setBackgroundColor(Color.TRANSPARENT);
        voiceSendText.setVisibility(GONE);
        voiceTime.setTextColor(colorBlue);
        voiceTime.setText("");

        circleBg.setVisibility(GONE);
        progressView.setVisibility(VISIBLE);
        progressView.setProgressColor(colorAlphaBlue);
        progressView.setProgress(0);
        //
        longClickBg.setImageResource(R.drawable.record_recording);
        longClickBg.setBackgroundResource(R.drawable.shape_voice_blue_circle);
        longClickBg.setVisibility(VISIBLE);

    }

    //切换点击模式和长按模式
    private void switchVoiceModel() {
        if (currentModle == VoiceInputModel.InitClick) {
            showLongClickModel();
        } else if (currentModle == VoiceInputModel.InitLongClick) {
            showClickModel();
        }
    }

    private void initVoiceModel() {
        if (currentModle == VoiceInputModel.InitClick
                || currentModle ==VoiceInputModel.ClickVoiceing
                || currentModle == VoiceInputModel.ClickVoicePause) {
            showClickModel();
        } else if (currentModle == VoiceInputModel.InitLongClick) {
            showLongClickModel();
        }
    }

    public void updateView(){
        if (currentModle ==VoiceInputModel.ClickVoiceing
                || currentModle == VoiceInputModel.ClickVoicePause) {
            initVoiceModel();
        }
    }


    //开始点击录音
    private void startClickRecording() {
        currentModle = VoiceInputModel.ClickVoiceing;
        circleBg.setImageResource(R.drawable.record_pause);
        voicePointView.setBackgroundResource(R.drawable.shape_voice_orange_circle);
        circleBg.setBackgroundResource(R.drawable.shape_voice_orange_circle);
        voiceModelSecend.setTextColor(colorOrange);//#
        actionView.setBackgroundColor(Color.TRANSPARENT);
        //
        if (voiceInputListener != null){
            voiceInputListener.showVoiceInputTip("录满60秒将自动发送，并启动下一条语音",colorOrange);
        }
        startRecoding();
    }

    //暂停点击录音
    private void pauseClickRecording() {
        currentModle = VoiceInputModel.ClickVoicePause;
        circleBg.setImageDrawable(null);
        voiceSendText.setVisibility(VISIBLE);
        voiceCancle.setVisibility(VISIBLE);
        //显示取消
        if (voiceInputListener != null){
            voiceInputListener.showVoiceInputTip("发送后可录制下一条",colorOrange);
        }
        onlyStopRecoding();
    }

    //
    private void sendClickRecording() {
        showClickModel();
        if (voiceLength > 0) {
            if (voiceRecorderCallback != null) {
                voiceRecorderCallback.onVoiceRecordComplete(getVoiceFilePath(), voiceLength);
            }
        }

    }


    //取消点击录音
    private void cancleClickRecording() {
        showClickModel();
    }


    //开始长按录音
    private void startLongClickRecording() {
        currentModle = VoiceInputModel.LongClickVoiceing;
        if (voiceInputListener != null){
            voiceInputListener.showVoiceInputTip("手指滑向此区域，取消录音",0xFF56B4F4);
        }
        startRecoding();
    }

    //取消长按录音
    private void cancelLongClickRecording() {
        showLongClickModel();
        if (voiceInputListener != null){
            voiceInputListener.hideVoiceInputTip();
        }
        discardRecording();
    }

    //完成长按录音
    private void finishLongClickRecording() {
        stopRecoding();//发送语音
        showLongClickModel();
        if (voiceInputListener != null){
            voiceInputListener.hideVoiceInputTip();
        }
    }

    private void recordCountDown(long secondes){
        if(secondes>0) {
            voiceTime.setVisibility(VISIBLE);
            voiceTime.setText(String.format("%ds", secondes));
            progressView.setProgress(secondes);
            if (currentModle == VoiceInputModel.ClickVoiceing) {
                if (secondes >= 50) { //展示倒计时
                    if (voiceInputListener != null) {
                        String tip = String.format("%d秒后将自动发出", 60 - secondes);
                        voiceInputListener.showVoiceInputTip(tip, colorRed);
                    }
                }

            } else if (currentModle == VoiceInputModel.LongClickVoiceing) {

            }
        }
    }

    private void recordCountDownFinish(){
        if (currentModle == VoiceInputModel.ClickVoiceing){
            stopRecoding();
            startClickRecording();
            //重新开始录音
            //发送语音
        } else if (currentModle == VoiceInputModel.LongClickVoiceing){
            //发送语音
            finishLongClickRecording();
        }

    }



    public void buildTimer(){
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(61000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    recordCountDown(times);
                    times++;
                }

                @Override
                public void onFinish() {
                    recordCountDownFinish();
                }
            };
        }
    }

    private void stopTimer(){
        if (countDownTimer != null){
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    private void startTimer(){
        times = 0;
        buildTimer();
        if (countDownTimer != null){
            countDownTimer.start();
        }
    }


    //开始录音
    private void startRecoding(){
        voiceLength = 0;
        if (ChatRowVoicePlayClickListener.currentPlayListener != null && ChatRowVoicePlayClickListener.isPlaying) {
            ChatRowVoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }
        try {
            wakeLock.acquire();
            voicePath =  voiceRecorder.startRecording();
            startTimer();//
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            if (voiceRecorder != null) {
                voiceRecorder.discardRecording();
            }
            Toast.makeText(mContext, "录音失败，请设置录音权限！", Toast.LENGTH_SHORT).show();
            initVoiceModel();//
            stopTimer();
            return;
        }
    }

    private void discardRecording(){
        try {
            // stop recording
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
            }
        } catch (Exception e) {
        }
        stopTimer();

    }

    private void onlyStopRecoding(){
        try {
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            voiceLength = voiceRecorder.stopRecoding();
            if (voiceLength > 0) {

            } else if (voiceLength == EMError.FILE_INVALID) {
                Toast.makeText(mContext, com.hyphenate.easeui.R.string.Recording_without_permission, Toast.LENGTH_SHORT).show();
            } else {
                initVoiceModel();
                Toast.makeText(mContext, com.hyphenate.easeui.R.string.The_recording_time_is_too_short, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
//            Toast.makeText(mContext, com.hyphenate.easeui.R.string.send_failure_please, Toast.LENGTH_SHORT).show();
        }
        stopTimer();
    }

    private void stopRecoding(){
        try {
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            voiceLength = voiceRecorder.stopRecoding();
            if (voiceLength > 0) {
                if (voiceRecorderCallback != null) {
                    voiceRecorderCallback.onVoiceRecordComplete(getVoiceFilePath(), voiceLength);
                }
            } else if (voiceLength == EMError.FILE_INVALID) {
                Toast.makeText(mContext, com.hyphenate.easeui.R.string.Recording_without_permission, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, com.hyphenate.easeui.R.string.The_recording_time_is_too_short, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
//            Toast.makeText(mContext, com.hyphenate.easeui.R.string.send_failure_please, Toast.LENGTH_SHORT).show();
        }
        stopTimer();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }

    //判断范围

//    private boolean ab(flo、at pointX,float pointY){
//
//
//        if (actionView.getX() )
//        return false;
//
//    }


    //界面状态
    public enum VoiceInputModel {
        InitClick,
        InitLongClick,
        ClickVoiceing,
        ClickVoicePause,
        LongClickVoiceing;
    }


    //输入过程中的回调
    interface VoiceInputListener {
        void showVoiceInputTip(String tip, int bgColor);

        void hideVoiceInputTip();

    }


    public void setVoiceInputListener(VoiceInputListener voiceInputListener) {
        this.voiceInputListener = voiceInputListener;
    }

    public void setVoiceRecorderCallback(VoiceRecorderCallback voiceRecorderCallback) {
        this.voiceRecorderCallback = voiceRecorderCallback;
    }



    public interface VoiceRecorderCallback {
        /**
         * on voice record complete
         *
         * @param voiceFilePath
         *            录音完毕后的文件路径
         * @param voiceTimeLength
         *            录音时长
         */
        void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength);
    }


    public boolean isRecording(){
        return voiceRecorder.isRecording();
    }


    public void stopRecorder(){
        onlyStopRecoding();
        voiceRecorder.discardRecording();
        initVoiceModel();
    }





    /******手势***/

//    @Override
//    public boolean onTouchEvent(MotionEvent e) {
//        switch (e.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                if (currentModle == VoiceInputModel.InitClick
//                        || currentModle == VoiceInputModel.InitLongClick
//                        || currentModle == VoiceInputModel.LongClickVoiceing) {
//
//                    downX = e.getX();
//                    downY = e.getY();
//                    return true;
//                }
//
//                break;
//
//            case MotionEvent.ACTION_MOVE:
//                distanceX = e.getX() - downX;
//                distanceY = e.getY() - downY;
//
//                if (currentModle == VoiceInputModel.LongClickVoiceing) {
//                    if (e.getY() < 0) {
//                        //
//                        if (voiceInputListener != null) {
//                            voiceInputListener.showVoiceInputTip("松开手指，取消发送", 0xFFFF6565);
//                        }
//                    } else {
//                        if (voiceInputListener != null) {
//                            voiceInputListener.showVoiceInputTip("手指滑向此区域，取消录音", 0xFF56B4F4);
//                        }
//                    }
//                }
//
//                break;
//
//            case MotionEvent.ACTION_UP:
//                if (currentModle == VoiceInputModel.InitClick
//                        || currentModle == VoiceInputModel.InitLongClick) {
//                    if (Math.abs(distanceY) < 50 && distanceX > 50) {
//                        switchVoiceModel();
//                    } else if (Math.abs(distanceY) < 50 && distanceX < -50) {
//                        switchVoiceModel();
//                    }
//                    return true;
//                } else if (currentModle == VoiceInputModel.LongClickVoiceing) {
//                    currentModle = VoiceInputModel.InitLongClick;
//                    if (voiceInputListener != null) {
//                        voiceInputListener.hideVoiceInputTip();
//                    }
//
//                    return true;
//                }
//
//
//                break;
//
//            case MotionEvent.ACTION_OUTSIDE:
//
//                break;
//
//        }
//
//        return false;
//
////        return detector.onTouchEvent(e);
//    }

    @Override
    public boolean onDown(MotionEvent e) {
        distanceScrollX = 0;
        distanceScrollY = 0;

        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {

//        if (e.getRawX() == actionView.getr)

        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        distanceScrollX = distanceX;
        distanceScrollY = distanceY;


//        if (currentModle == VoiceInputModel.InitClick
//                || currentModle == VoiceInputModel.InitLongClick) {
//
//            if (Math.abs(distanceY) < 20 && distanceX > 40){
//                switchVoiceModel();
//            } else if (Math.abs(distanceY) < 20 && distanceX < -40){
//                switchVoiceModel();
//            }
//        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
//        actionView.getx

        if (e.getRawX() == 100) {


        }

//        if (actionView.getv)

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//        if (currentModle == VoiceInputModel.InitClick
//                || currentModle == VoiceInputModel.InitLongClick) {
//            if (Math.abs(distanceScrollY) < 20 && distanceScrollX > 30) {
//                switchVoiceModel();
//            } else if (Math.abs(distanceScrollY) < 20 && distanceScrollX < -30) {
//                switchVoiceModel();
//            }
//        }

        return false;
    }

    /******手势***/
}
